<route lang="jsonc" type="page">
{
  "layout": "default",
  "style": {
    "navigationStyle": "custom"
  }
}
</route>

<script lang="ts" setup>
import { ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { codeLogin, login, sendMobileCode } from '@/api/login'
import Navigation from '@/components/Navigation/Navigation.vue'

const route = useRoute()
const router = useRouter()
const title = ref('注册')
const bool = ref(false)
const phone = ref('')
const password = ref('')
const verificationCode = ref('')
const showPassword = ref(false)
const agreed = ref(false)

// 错误提示状态
const phoneError = ref('')
const passwordError = ref('')

// 验证码相关状态
const countdown = ref(0)
const canSendCode = ref(true)

// 验证手机号
function validatePhone() {
  if (!phone.value) {
    phoneError.value = '请输入手机号'
    return false
  }
  if (!/^1[3-9]\d{9}$/.test(phone.value)) {
    phoneError.value = '请输入正确的手机号'
    return false
  }
  phoneError.value = ''
  return true
}

// 验证密码/验证码
function validatePassword() {
  if (bool.value) {
    // 验证码模式
    if (!verificationCode.value) {
      passwordError.value = '请输入验证码'
      return false
    }
    if (!/^\d{6}$/.test(verificationCode.value)) {
      passwordError.value = '请输入6位验证码'
      return false
    }
  }
  else {
    // 密码模式
    if (!password.value) {
      passwordError.value = '请输入密码'
      return false
    }
    if (password.value.length < 6) {
      passwordError.value = '密码长度不能少于6位'
      return false
    }
  }

  passwordError.value = ''
  return true
}

// 验证表单
function validateForm() {
  const phoneValid = validatePhone()
  const passwordValid = validatePassword()
  return phoneValid && passwordValid
}

async function handleLogin() {
  if (!validateForm()) {
    return
  }

  if (!agreed.value) {
    uni.showToast({
      title: '请勾选我已同意',
      icon: 'none',
    })
    return
  }

  // 登录逻辑
  if (bool.value) {
    console.log('短信验证码登录', { phone: phone.value, code: verificationCode.value })
    await codeLogin({ mobile: phone.value, code: verificationCode.value }).then((res) => {
      router.push('/pages/home/home')
      console.log(res, 1111)
      localStorage.setItem('token', res.data.token)
    })
  }
  else {
    await login({ mobile: phone.value, password: password.value }).then((res) => {
      router.push('/pages/home/home')
      console.log(res, 1111)
       localStorage.setItem('token', res.data.token)
    })
    console.log('密码登录', { phone: phone.value, password: password.value })
  }
}

function togglePassword() {
  showPassword.value = !showPassword.value
}

function goToRegister() {
  // 第三方登录
}

function goToPhoneLogin() {
  // 切换到手机验证码登录
  bool.value = !bool.value
  phoneError.value = ''
  passwordError.value = ''
  verificationCode.value = ''
}

function goToForgotPassword() {
  // 跳转到忘记密码页面
  console.log('跳转忘记密码页面')
}

// 发送验证码
async function sendVerificationCode() {
  if (!validatePhone()) {
    return
  }

  if (!canSendCode.value) {
    return
  }

  // 发送验证码逻辑
  await sendMobileCode({ mobile: phone.value, type: 'login' }).then((res) => {
    console.log('验证码为:', res.data)
  })

  // 开始倒计时
  canSendCode.value = false
  countdown.value = 60

  const timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(timer)
      canSendCode.value = true
      countdown.value = 0
    }
  }, 1000)

  // 显示发送成功提示
  uni.showToast({
    title: '验证码已发送',
    icon: 'success',
  })
}

// 输入时清除错误提示
function onPhoneInput() {
  if (phoneError.value) {
    phoneError.value = ''
  }
}

function onPasswordInput() {
  if (passwordError.value) {
    passwordError.value = ''
  }
}
</script>

<template>
  <view class="login-page">
    <Navigation :title="title" />

    <view class="login-content">
      <!-- 标题区域 -->
      <view class="title-section">
        <text class="main-title">{{ bool ? "短信验证码登录" : "密码登录" }}</text>
        <view class="sub-title" @click="goToPhoneLogin">
          <text>{{ bool ? "密码登录" : "短信验证码登录" }}</text>
          <wd-icon name="arrow-right" size="16" />
        </view>
      </view>

      <!-- 输入框区域 -->
      <view class="input-section">
        <view class="input-item">
          <wd-input
            v-model="phone"
            placeholder="请输入手机号"
            type="number"
            :maxlength="11"
            clearable
            @input="onPhoneInput"
          />
          <view class="error-message">
            {{ phoneError || ' ' }}
          </view>
        </view>

        <view class="input-item">
          <view class="input-container">
            <wd-input
              v-if="!bool"
              v-model="password"
              placeholder="请输入密码"
              :type="showPassword ? 'text' : 'password'"
              clearable
              @input="onPasswordInput"
            >
              <template #suffix>
                <wd-icon
                  :name="showPassword ? 'eye-on' : 'eye-off'"
                  size="18"
                  class="eye-icon"
                  @click="togglePassword"
                />
              </template>
            </wd-input>

            <view v-else class="verification-input">
              <wd-input
                v-model="verificationCode"
                placeholder="请输入验证码"
                type="number"
                :maxlength="6"
                clearable
                @input="onPasswordInput"
              />
              <view
                class="send-code-text disabled"
           
                @click="sendVerificationCode"
              >
                {{ canSendCode ? '发送验证码' : `${countdown}s` }}
              </view>
            </view>
          </view>

          <view class="error-message">
            {{ passwordError || ' ' }}
          </view>
        </view>
      </view>

      <!-- 协议勾选区域 -->
      <view class="agreement-section">
        <wd-checkbox v-model="agreed" shape="circle">
          <text class="agreement-text">
            我已同意
            <text class="link-text">用户协议</text>
            及
            <text class="link-text">隐私协议</text>
          </text>
        </wd-checkbox>
      </view>

      <!-- 登录按钮 -->
      <view class="button-section">
        <wd-button
          type="success"
          size="large"
          block
          @click="handleLogin"
        >
          登录
        </wd-button>
      </view>

      <!-- 忘记密码 -->
      <view class="forgot-section">
        <text class="forgot-text" @click="goToForgotPassword">忘记密码?</text>
      </view>

      <!-- 第三方登录 -->
      <view class="third-party-section">
        <view class="divider">
          <view class="divider-line" />
          <text class="divider-text">第三方登录</text>
          <view class="divider-line" />
        </view>

        <view class="third-party-icons">
          <view class="icon-item" @click="goToRegister">
            <view class="icon-circle">
              <img src="/static/QQ.svg" alt="">
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.login-page {
  min-height: 100vh;
  background-color: #fff;
}

.login-content {
  padding: 40rpx;
  padding-top: 30rpx;
}

.title-section {
  margin-bottom: 80rpx;
  display: flex;
  justify-content: space-between;

  .main-title {
    color: #333;
    display: block;
    margin-bottom: 32rpx;
    color: #121826;
    font-family: PingFang SC;
    font-weight: medium;
    font-size: 48rpx;
    line-height: 72rpx;
    letter-spacing: 0rpx;
    text-align: left;
  }

  .sub-title {
    display: flex;
    align-items: center;
    color: #666;
    font-size: 28rpx;

    text {
      margin-right: 8rpx;
    }
  }
}

.input-section {
  margin-bottom: 60rpx;

  .input-item {
    margin-bottom: 40rpx;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .input-container {
    min-height: 80rpx;
    display: flex;
    align-items: center;
  }

  .wd-input {
    margin-bottom: 0;
  }

  .input-container > .wd-input {
    flex: 1;
    width: 100%;
  }

  .eye-icon {
    color: #999;
    cursor: pointer;
  }

  .verification-input {
    display: flex;
    align-items: center;
    gap: 20rpx;
    width: 100%;

    .wd-input {
      flex: 1;
    }

    .send-code-text {
      min-width: 160rpx;
      height: 80rpx;
      font-size: 24rpx;
      color: #018d71;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      user-select: none;

      &.disabled {
        color: #16c2a3;
        cursor: not-allowed;
      }
    }
  }

  .error-message {
    color: #ff4757;
    font-size: 24rpx;
    margin-top: 8rpx;
    min-height: 32rpx;
    line-height: 32rpx;
    padding-left: 8rpx;
  }
}

.agreement-section {
  margin-bottom: 60rpx;

  .agreement-text {
    font-size: 28rpx;
    color: #666;

    .link-text {
      color: #16c2a3;
    }
  }
}

.button-section {
  margin-bottom: 40rpx;
}

.forgot-section {
  text-align: center;
  margin-bottom: 120rpx;

  .forgot-text {
    color: #999;
    font-size: 28rpx;
    cursor: pointer;
  }
}

.third-party-section {
  .divider {
    display: flex;
    align-items: center;
    margin-bottom: 29rpx;

    .divider-line {
      flex: 1;
      height: 2rpx;
      background-color: #eee;
    }

    .divider-text {
      margin: 0 40rpx;
      color: #999;
      font-size: 28rpx;
    }
  }

  .third-party-icons {
    display: flex;
    justify-content: center;

    .icon-item {
      .icon-circle {
        width: 100rpx;
        height: 90rpx;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        img {
          width: 60rpx;
          height: 60rpx;
        }
      }
    }
  }
}
</style>
